package com.lxh.baselibray.net;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lxh.baselibray.BaseApplication;
import com.lxh.baselibray.base.BaseResponce;
import com.lxh.baselibray.constant.ARouterConfig;
import com.lxh.baselibray.util.ARouterUtils;
import com.lxh.baselibray.util.CacheUtils;
import com.lxh.baselibray.util.ObjectUtils;


import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public abstract class HttpCallBack<T> implements Callback<T> {
    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response!=null&& response.body() !=null&&response.isSuccessful()){
            BaseResponce baseResponce = new Gson().fromJson(new Gson().toJson(response.body()), BaseResponce.class);
            if (baseResponce.getCode()==401){
                //弹出提示用户帐号在其它地方登录
                showRemindDialog();
            }else {
                onSuccess(call,response);
            }
        }else {
            onFailed();
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        onFailed();
    }

    public abstract void onSuccess(Call<T> call, Response<T> response);

    public  void onFailed(){
        Toast.makeText(BaseApplication.getApplication(),"网络请求异常",Toast.LENGTH_LONG).show();
    };

    private void showRemindDialog() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                final Activity taskTop = BaseApplication.getActivityManage().getTaskTop();
                if (ObjectUtils.isEmpty(taskTop))return;
                AlertDialog dialog=null;
                AlertDialog.Builder builder=new AlertDialog.Builder(taskTop)
                        .setCancelable(false)
                        .setMessage("您的帐号在其它终端登录，请重新登录")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                CacheUtils.clearShareFCacheData();
                                ARouterUtils.jump(ARouterConfig.Home_login_act);
                                BaseApplication.getActivityManage().finishAll();
                                dialog.dismiss();
                            }
                        });
                dialog= builder.create();
                if (!dialog.isShowing()){
                    dialog.show();
                }
            }
        });
    }
}
